<?php
/** require:
 *  __PHY_LIB
 */
require_once(__PHY_LIB . "/class/Item.class.php");

class Food extends Item {
/// definition and constructor ///
	function Food($id=0, $field="") {
		Query::Query();
		$this->cfgKeyField("id");
		$this->cfgAllField("id,nation,city,restaurant,title,description,image_s,image_m,image_b");
		$this->cfgTable("unit_food");
		if ("" == $field || "*" == $field) {
			$this->cfgField($this->mAllField);
		}
		else {
			$this->cfgField($field);
		}
		if (0 < $id) {
			$this->cfgWhere($this->mKeyField . "=" . $id);
			$this->load();
		}
		else {
			$this->set($this->mKeyField, $id);
		}
	}

	function loadByName($sName) {
		$this->cfgWhere("name='".addslashes($sName)."'");
		$this->load();
	}

	function invalid() {
		return false;
	}

	/// 字段图片 ///
	function calcFileUrl($sField) {
		if (!(0 < $this->getID())) { return false; }
		$sNumber = str_pad($this->getID(), 6, '0', STR_PAD_LEFT);
		$sUrl = "/food/".substr($sNumber, 0, 3)."/".substr($sNumber, 3, 3)."/{$sField}.png";
		return $sUrl;
	}
	function setFile($sField, $sSrcPath) {
		$sUrl = $this->calcFileUrl($sField);
		mkdir_plus(dirname(__PHY_STO.$sUrl));
		if ($sUrl && move_uploaded_file($sSrcPath, __PHY_STO.$sUrl)) {
			$this->set($sField, $sUrl);
			return true;
		}
		else {
			return false;
		}
	}

	/// 插图照片 ///
	function addImage($sSrcPath) {
		if (!(0 < $this->getID())) { return false; }
		$sNumber = str_pad($this->getID(), 6, '0', STR_PAD_LEFT);
		$sName = date('YmdHis');
		$sUrl = "/food/".substr($sNumber, 0, 3)."/".substr($sNumber, 3, 3)."/{$sName}.png";
		mkdir_plus(dirname(__PHY_STO.$sUrl));
		if ($sUrl && move_uploaded_file($sSrcPath, __PHY_STO.$sUrl)) {
			$sQ = "INSERT INTO unit_food_image SET food_id='".$this->getID()."',image_m='".addslashes($sUrl)."'";
			$this->loadQuery($sQ);
			return $sUrl;
		}
		else {
			return false;
		}
	}
	function fetchImages() {
		if (!(0 < $this->getID())) { return false; }
		$oList = new ItemList();
		$oList->cfgTable('unit_food_image');
		$oList->cfgWhere("food_id='".$this->getID()."'");
		$oList->cfgOrder("id");
		$oList->load();
		return $oList->fetchArray();
	}
	function deleteImage($nImageID) {
		if (!(0 < $this->getID())) { return false; }
		$oOne = new Item();
		$oOne->cfgTable('unit_food_image');
		$oOne->cfgWhere("id='".(int)$nImageID."'");
		if ($oOne->delete()) { return true; }
		else { return false; }
	}

} /// end class Food.

class FoodList extends ItemList {
	/// definition and constructor ///
	function FoodList($tablename=null) {
		ItemList::ItemList();
		$this->cfgClass("Food");
		$this->cfgKeyField("id");
		$this->cfgAllField("id,nation,city,restaurant,title,description,image_s,image_m,image_b");
		$this->cfgTable(null == $tablename ? "unit_food" : $tablename);
	}

} /// end class FoodList.
?>
